<template>
  <div>
    <j-upload v-model='list' accept='.png,.jpg,.jpeg' fileType='image' class='avatar-uploader' :number='number'
              :text='text'
              :returnUrl='false' @change='uploadImage'></j-upload>
    <span v-if='value&&value.length'>
      <span v-for='(row,index) in value' :key='index'>
         <a-input v-model='row.productCode' placeholder='商品编号' class='form-input'></a-input>
      </span>
    </span>
    <div v-else style='height: 40px'></div>


  </div>
</template>

<script>
import JUpload from '@comp/cn-form/JUpload'

export default {
  name: 'test',
  components: { JUpload },
  props: {
    text: {
      type: String,
      required: false,
      default: '点击上传'
    },
    value: {
      type: [String, Array],
      required: false,
      default: () => []
    },
    // update-begin- --- author:wangshuai ------ date:20190929 ---- for:Jupload组件增加是否能够点击
    disabled: {
      type: Boolean,
      required: false,
      default: false
    },
    number: {
      type: Number,
      required: false,
      default: 0
    }
  },
  data() {
    return {
      list: []
    }
  },
  watch: {
    value: {
      immediate: true,
      handler() {
        if (!this.value) {
          this.value = []
        }
        let val = this.value
        if (val instanceof Array) {
          this.initFileListArr(val)
          this.list = JSON.parse(JSON.stringify(this.value))
        }
        this.$emit('change', this.value)
      }
    }
  },
  methods: {
    generateUUID(withSeparator = true) {
      let d = new Date().getTime()
      if (window.performance && typeof window.performance.now === 'function') {
        d += performance.now()
      }
      const tpl = withSeparator ? 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx' : 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'
      return tpl.replace(/[xy]/g, function(c) {
        const r = (d + Math.random() * 16) % 16 | 0
        d = Math.floor(d / 16)
        return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16)
      })
    },
    initFileListArr(val) {

    },
    uploadImage(fileList) {
      if (fileList.length == this.value.length) {
        return
      }
      if (fileList.length < this.value.length) {
        let list = this.value.filter(item => {
          let index = fileList.findIndex(v => v.url == item.url)
          if (index != -1) {
            return item
          }
        })
        console.log(list)
        this.value = list
      }
      if (fileList.length > this.value.length) {
        let id = this.generateUUID
        this.value.push({
          ...fileList[fileList.length - 1],
          productCode: '',
          id
        })
      }
    }
  },
  model: {
    prop: 'value',
    event: 'change'
  }
}


</script>

<style scoped>
.form-input {
  width: 104px;
  margin-right: 8px;
}
</style>